<template>
  <div>
    <div class="header">
      <span class="iconfont iconjiantou2" @click="back"></span>
      <div class="middle">
        <span class="iconfont iconsearch"></span>
        <input type="text" v-model="searchText" class="searchText" placeholder="请搜索" />
      </div>
      <div class="btn" @click="search">搜索</div>
    </div>
    <div v-if="resultList.length > 0">
      <post :post="post" v-for="(post,index) in resultList" :key="index"></post>
    </div>
    <div class="suggestion" v-else>
      <div class="history">
        <h2>历史记录</h2>
         <span v-for="(item, index) in historyList" :key="index"
                @click="searchByWord(item)">
                    {{item}}
                </span>
      </div>
      <div class="hot">
        <h2>热门搜索</h2>
        <span v-for="(item, index) in hotList" :key="index" @click="searchByWord(item)">{{item}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import post from "../components/post";
export default {
  components: {
    post
  },
  data() {
    return {
      searchText: "",
      resultList: [],
      hotList: [],
      historyList: localStorage.getItem('searchHistory')? JSON.parse(localStorage.getItem('searchHistory')) : []
    };
  },
  watch:{
searchText(){
if(this.searchText==''){
    this.resultList = [];
}
},
historyList(){
    const strHistory = JSON.stringify(this.historyList);
localStorage.setItem('searchHistory', strHistory);
}
  },

  methods: {
      back() {
            if (this.searchText) {
                this.searchText = "";
            }else {
                this.$router.back();
            }
        },
    search() {
      this.searchText;
      this.$axios({
        url: "/post_search",
        method: "get",
        params: {
          keyword: this.searchText
        }
      }).then(res => {
        const { data } = res.data;
        console.log(data);

        this.resultList = data;
        if (this.historyList.indexOf(this.searchText) < 0) {
                    this.historyList.push(this.searchText)
                }
      });
    },
    getHotList() {
    this.hotList = ["关晓彤", "王祖贤", "女歌手"];
  },
  searchByWord(item) {
    this.searchText = item;
    this.search();
  },
  },
  
  
    mounted() {
    this.getHotList();
  },

};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2.778vw;
}
.middle {
  width: 65.667vw;
  height: 10.556vw;
  line-height: 10.556vw;
  border: 1px solid #888;
  border-radius: 5.278vw;
  padding: 0 4.167vw;
  .searchText {
    height: 9vw;
    line-height: 9vw;
    width: 55.556vw;
    border: none;
    outline: none;
  }
  .history, .hot {
        padding: 0 2.778vw;
    }
    .history {
        min-height: 55.556vw;
        border-bottom: 1px solid #eee;
        margin-bottom: 5.556vw;
    }
}
</style>